<?php
session_start();

// 检查是否已经安装
$install_file = '../data/installed.txt';
$is_installed = file_exists($install_file);

if ($is_installed) {
    header('Location: ../chat/');
    exit;
}

$error_message = '';
$success_message = '';

if ($_POST) {
    $db_host = trim($_POST['db_host'] ?? '');
    $db_name = trim($_POST['db_name'] ?? '');
    $db_user = trim($_POST['db_user'] ?? '');
    $db_pass = trim($_POST['db_pass'] ?? '');
    $api_key = trim($_POST['api_key'] ?? '');
    $base_url = trim($_POST['base_url'] ?? '');
    $admin_user = trim($_POST['admin_user'] ?? '');
    $admin_pass = trim($_POST['admin_pass'] ?? '');
    $default_model = trim($_POST['default_model'] ?? '');
    $custom_model = trim($_POST['custom_model'] ?? '');

    // 验证输入
    if (empty($db_host) || empty($db_name) || empty($db_user) || empty($api_key) || empty($base_url) || empty($admin_user) || empty($admin_pass)) {
        $error_message = '请填写所有必需字段';
    } else {
        // 选择模型 - 如果选择了自定义模型，则使用自定义模型
        $selected_model = $default_model === 'custom' ? $custom_model : $default_model;
        
        if (empty($selected_model)) {
            $error_message = '请选择或输入AI模型';
        } else {
            try {
                // 测试数据库连接
                $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                
                // 创建必要的表
                $tables_sql = "
                CREATE TABLE IF NOT EXISTS `chat_history` (
                    `id` INT AUTO_INCREMENT PRIMARY KEY,
                    `user_ip` VARCHAR(45) NOT NULL,
                    `message` TEXT NOT NULL,
                    `response` TEXT NOT NULL,
                    `timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    `session_id` VARCHAR(255) DEFAULT NULL
                );
                
                CREATE TABLE IF NOT EXISTS `users` (
                    `id` INT AUTO_INCREMENT PRIMARY KEY,
                    `ip_address` VARCHAR(45) NOT NULL UNIQUE,
                    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                );
                
                CREATE TABLE IF NOT EXISTS `settings` (
                    `id` INT AUTO_INCREMENT PRIMARY KEY,
                    `setting_key` VARCHAR(255) NOT NULL UNIQUE,
                    `setting_value` TEXT
                );
                ";
                
                foreach (explode(";\n", $tables_sql) as $sql) {
                    $sql = trim($sql);
                    if (!empty($sql)) {
                        $pdo->exec($sql);
                    }
                }
                
                // 保存配置到文件
                $config_content = "<?php\n";
                $config_content .= "\$db_host = '$db_host';\n";
                $config_content .= "\$db_name = '$db_name';\n";
                $config_content .= "\$db_user = '$db_user';\n";
                $config_content .= "\$db_pass = '$db_pass';\n";
                $config_content .= "\$api_key = '$api_key';\n";
                $config_content .= "\$base_url = '$base_url';\n";
                $config_content .= "\$default_model = '$selected_model';\n";
                $config_content .= "?>";
                
                file_put_contents('../data/config.php', $config_content);
                
                // 创建管理员账户
                $hashed_admin_pass = password_hash($admin_pass, PASSWORD_DEFAULT);
                $admin_config = [
                    'username' => $admin_user,
                    'password' => $hashed_admin_pass
                ];
                file_put_contents('../data/admin.json', json_encode($admin_config));
                
                // 创建已安装标记文件
                file_put_contents($install_file, date('Y-m-d H:i:s'));
                
                $success_message = '安装成功！正在跳转到聊天界面...';
                
                // 跳转到聊天界面
                header('Refresh: 2; url=../chat/');
            } catch (PDOException $e) {
                $error_message = '数据库连接失败: ' . $e->getMessage();
            } catch (Exception $e) {
                $error_message = '安装过程中发生错误: ' . $e->getMessage();
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>lanxAI - 首个览星自研发AI - 安装界面</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            margin: 0;
            padding: 0;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .install-container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 600px;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .header h1 {
            color: #333;
            margin-bottom: 10px;
        }
        .header p {
            color: #666;
            margin: 0;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }
        .form-group input, .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
            box-sizing: border-box;
        }
        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 5px rgba(102, 126, 234, 0.3);
        }
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            width: 100%;
        }
        .btn:hover {
            opacity: 0.9;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 15px;
            border: 1px solid #f5c6cb;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 15px;
            border: 1px solid #c3e6cb;
        }
        .model-selector {
            display: flex;
            gap: 10px;
        }
        .model-selector > div {
            flex: 1;
        }
        .model-selector select, .model-selector input {
            margin-top: 5px;
        }
        .footer {
            text-align: center;
            margin-top: 20px;
            color: #666;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="install-container">
        <div class="header">
            <h1>lanxAI 安装向导</h1>
            <p>首个览星自研发AI</p>
        </div>
        
        <?php if ($error_message): ?>
            <div class="error"><?php echo htmlspecialchars($error_message); ?></div>
        <?php endif; ?>
        
        <?php if ($success_message): ?>
            <div class="success"><?php echo htmlspecialchars($success_message); ?></div>
        <?php endif; ?>
        
        <form method="post" id="installForm">
            <div class="form-group">
                <label for="db_host">数据库主机 (Database Host)</label>
                <input type="text" id="db_host" name="db_host" value="localhost" required>
            </div>
            
            <div class="form-group">
                <label for="db_name">数据库名称 (Database Name)</label>
                <input type="text" id="db_name" name="db_name" value="lanxai" required>
            </div>
            
            <div class="form-group">
                <label for="db_user">数据库用户名 (Database User)</label>
                <input type="text" id="db_user" name="db_user" required>
            </div>
            
            <div class="form-group">
                <label for="db_pass">数据库密码 (Database Password)</label>
                <input type="password" id="db_pass" name="db_pass">
            </div>
            
            <div class="form-group">
                <label for="api_key">API密钥 (API Key)</label>
                <input type="password" id="api_key" name="api_key" required placeholder="输入您的API密钥">
            </div>
            
            <div class="form-group">
                <label for="base_url">API基础URL (Base URL)</label>
                <input type="url" id="base_url" name="base_url" value="https://apis.iflow.cn/v1" required placeholder="https://apis.iflow.cn/v1">
                <small>提示: 这是API请求的基础URL</small>
            </div>
            
            <div class="form-group">
                <label>AI模型选择</label>
                <div class="model-selector">
                    <div>
                        <select id="default_model" name="default_model" onchange="toggleCustomModel()">
                            <option value="gpt-3.5-turbo">GPT-3.5 Turbo</option>
                            <option value="gpt-4">GPT-4</option>
                            <option value="gpt-4-turbo">GPT-4 Turbo</option>
                            <option value="custom">自定义模型</option>
                        </select>
                    </div>
                    <div>
                        <input type="text" id="custom_model" name="custom_model" placeholder="输入自定义模型名称" disabled>
                    </div>
                </div>
            </div>
            
            <div class="form-group">
                <label for="admin_user">管理员用户名</label>
                <input type="text" id="admin_user" name="admin_user" required>
            </div>
            
            <div class="form-group">
                <label for="admin_pass">管理员密码</label>
                <input type="password" id="admin_pass" name="admin_pass" required>
            </div>
            
            <button type="submit" class="btn">开始安装</button>
        </form>
        
        <div class="footer">
            <p>LANX开源AI</p>
        </div>
    </div>

    <script>
        function toggleCustomModel() {
            const defaultModel = document.getElementById('default_model');
            const customModel = document.getElementById('custom_model');
            
            if (defaultModel.value === 'custom') {
                customModel.disabled = false;
                customModel.required = true;
            } else {
                customModel.disabled = true;
                customModel.required = false;
            }
        }
        
        // 初始化时检查模型选择
        document.addEventListener('DOMContentLoaded', function() {
            toggleCustomModel();
        });
    </script>
</body>
</html>